import bcrypt from 'bcryptjs'

import { loginByUserName, registerByUserName, findUser, deleteUser } from '../service/UserService.js'
import jwt from 'jsonwebtoken'

import { UserEmptyValidate, UserVerifyValidate, UserPasswordValidate } from '../middleware/UserValidate.js'
import { TokenValidate } from '../middleware/TokenValidate.js';
import {
  request,
  summary,
  body,
  tags,
  middlewares,
  path,
  description,
  orderAll,
  query,
  middlewaresAll,
  prefix
} from 'koa-swagger-decorator'

const tag = tags(['User'])
const userSchema = {
  name: { type: 'string', required: true },
  password: { type: 'string', required: true },
  phone: { type: 'string', required: true }
}

@prefix("/user")
export default class UserController {

  @request('post', '/register')
  @summary('注册一个用户 可以匿名请求')
  @description('example of api')
  @middlewares([UserEmptyValidate(), UserVerifyValidate(), UserPasswordValidate()])
  @tag
  @body(userSchema)
  async register (ctx) {
    const { username, password, phone } = ctx.request.body

    try {
      const res = await registerByUserName(username, password, phone)
      //ctx.body = res
      ctx.success(res)
    }
    catch (err) {
      ctx.fail(-1, '注册失败')
    }
  }

  @request('post', '/login')
  @summary('登陆')
  @description('example of api')
  @tag
  async login (ctx) {
    console.log(ctx.request.body);
    //结构
    const { username, password } = ctx.request.body

    try {
      const res = await findUser({ username })

      //判断密码
      if (res) {
        if (bcrypt.compareSync(password, res.password)) {
          res.lastLoginTime = new Date();
          if (res.loginTimes) {
            res.loginTimes = res.loginTimes
          }
          else {
            res.loginTimes = 1
          }
          res.save()

          //签发token
          let token = jwt.sign({
            id: res.id,
            username: res.username,
            phone: res.phone
          }, process.env.JWT_SCRET, {
            expiresIn: '1h'
          })
          ctx.success({ token: token, info: res })
        }
        else {
          ctx.fail(400, '密码错误')
        }
        //ctx.body = res

      }
      else {
        ctx.fail(400, '用户名不存在')
      }

    } catch (err) {
      ctx.fail(-1, '登录失败')
    }

  }

  @request('get', '/getUserInfo')
  @summary('获取用户信息')
  @middlewares([TokenValidate()])
  @tag
  async getUserInfo (ctx) {

    try {
      const res = await findUser({ id: ctx.state.user.id })
      ctx.success(res)
    }
    catch (err) {
      ctx.fail(-1, '查询失败')
    }
  }

  @request('get', '/getById')
  @summary('根据ID用户获取信息')
  @middlewares([TokenValidate()])
  @query({
    id: { type: 'string', required: true, description: '用户id' }
  })
  @tag
  async getById (ctx) {
    try {
      const res = await findUser({ id: ctx.request.query.id })
      ctx.success(res)
    }
    catch (err) {
      ctx.fail(-1, '查询失败')
    }
  }

  @request('delete', '/user/del')
  @summary('删除用户')
  @tag
  @query({
    id: { type: 'string', required: true, description: '用户id' }
  })
  async deleteUser (ctx) {
    try {
      await deleteUser(ctx.request.query.id)
      ctx.success({ id: ctx.request.query.id })
    }
    catch (err) {
      ctx.fail(-1, '删除失败')
    }
  }
}